#include "Dict.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

struct sDict
{
	Abb abb;
	int tam;
};

Dict
dict_empty (void)
{
	Dict retorno =NULL;
	retorno=(Dict)calloc(1,sizeof(struct sDict));
	if(retorno == NULL)
		return NULL;
	retorno -> abb = abb_empty();
	retorno -> tam = 0;
	return retorno;	
}


void
dict_add (Dict d, Word w, Def f)
{
	Key aux1=NULL;
	Data aux2=NULL;	
	assert(d != NULL);
	aux1=key_fromString(w);
	aux2=data_fromString(f);
	abb_add(d -> abb,aux1,aux2);
	d -> tam = abb_length(d->abb);
	data_destroy(aux2);
	key_destroy(aux1);
}

Bool
dict_exists (Dict d, Word w)
{
	Key aux1 = NULL;
	Bool aux2 = FALSE;
	if(d == NULL)
		return FALSE;
	aux1=key_fromString(w);
	aux2=abb_exists(d -> abb,aux1);
	key_destroy(aux1);
	return aux2;
}

Def
dict_search (Dict d, Word w)
{
	Key k;
	Data da; 
	char *ptr;
	k = key_fromString(w);
	da=abb_search(d -> abb,k);
	ptr=data_toString(da);
	data_destroy(da);
	key_destroy(k);
	return ptr;
	
}

void
dict_del (Dict d, Key k)
{
	assert(d != NULL);
	abb_del(d -> abb, k);
	d -> tam = abb_length(d->abb);
}

void
dict_pprint (Dict d)
{
	assert(d != NULL);
	abb_pprint(d -> abb);
}

int
dict_length (Dict d)
{
	if(d == NULL)
		return -1;
	else
		return d -> tam;
}

Dict
dict_destroy (Dict d)
{
	if(d == NULL)
		return NULL;
	else
	{
		abb_destroy(d -> abb);
		free(d);
		d = NULL;
		return d;
	}
}

Dict
dict_fromFile(char *nomfile)
{
	Dict d = dict_empty();

	if(d == NULL)
		return NULL;
	else
	{
		d -> abb = abb_destroy(d -> abb);
		d -> abb = abb_fromFile(nomfile);
		d -> tam = abb_length(d -> abb);
		return d;
	}
}

void
dict_toFile(char *nomfile, Dict d)
{
	assert(d != NULL);
	abb_toFile(nomfile , d -> abb);
}

Bool balanceo(Dict d)
{
	return invariante(d -> abb);
}
